package com.kamistoat.base;

import com.google.common.collect.Ordering;
import com.sun.deploy.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;

public class Ordering_Demo {
    public static void main(String[] args) {
        //1. 最原始的Ordering用法，和Comparator完全相同的用法，实现 compare方法
        Ordering<String> byLengthOrdering = new Ordering<String>() {
            // 返回负数，left在前。返回正数，right在前。返回0，相等
            @Override
            public int compare(String left, String right) {
                // return Integer.compare(left.length(), right.length());
                return left.length() - right.length();
            }
        };
        ArrayList<String> list = new ArrayList<>();
        list.add("wwwwww");
        list.add("oo");
        list.add("vvv");
        Collections.sort(list, byLengthOrdering);

        // 2. 直接使用Ordering提供的现成Comparetor
        Collections.sort(list, Ordering.usingToString());

        // 3. 链式调用--compound
        // 构建一个排序器，按照name首字母排序
        Ordering<Student_Ordering> nameOrdering = new Ordering<Student_Ordering>() {
            @Override
            public int compare(Student_Ordering left, Student_Ordering right) {
                return left.getName().charAt(0) - right.getName().charAt(0);
            }
        };

        // 构建一个排序器，按照num大小排序
        Ordering<Student_Ordering> numOrdering = new Ordering<Student_Ordering>() {
            @Override
            public int compare(Student_Ordering left, Student_Ordering right) {
                return left.getNum() - right.getNum();
            }
        };

        ArrayList<Student_Ordering> studentOrderings = new ArrayList<>();
        studentOrderings.add(new Student_Ordering(5, "Zte"));
        studentOrderings.add(new Student_Ordering(1, "Zoh"));
        studentOrderings.add(new Student_Ordering(10, "Albt"));
        // 使用链式调用。先按照name首字母排序，当name首字母相同时，按照num大小排序
        // 上面的例子进行排序后的结果为 10 1 5
        Collections.sort(studentOrderings, nameOrdering.compound(numOrdering));

        // 4. 链式调用--onResultOf
        // 上面的例子进行排序后的结果为 1 5 10
        Collections.sort(studentOrderings, numOrdering.onResultOf(student_ordering -> {
            // 类似stream操作，对列表所有元素做遍历操作
            student_ordering.setName("王五");
            // 注意最终必须手动显式执行 return.
            // 经过实验，return任何Student_Ordering类实例都可以，真正参与排序的是上面对原始 student_ordering 的排序。
            return student_ordering;
        }));


    }
}

class Student_Ordering {
    int num;
    String name;

    public Student_Ordering(int num, String name) {
        this.num = num;
        this.name = name;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
